import React, {useEffect, useState} from 'react';
import {Table, Button, Modal, Form, Input, Select, message, Space, Input as AntInput} from 'antd';
import TeacherModal from "./component/TeacherModal.jsx";
import {
    addTeacherInfo,
    batchDeleteTeacherInfo,
    deleteTeacherInfo,
    getTeacherInfo,
    updateTeacherInfo
} from "../../api/teacher.js";

const {Option} = Select;

const TeacherPage = () => {
    const [data, setData] = useState([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editingRecord, setEditingRecord] = useState(null);
    const [form] = Form.useForm();
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [searchKeyword, setSearchKeyword] = useState('');
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        fetchTeacherInfo();
    }, []);
    const fetchTeacherInfo = async () => {
        setLoading(true);
        try {
            const res = await getTeacherInfo(null);
            setData(res.data);
        } catch (error) {
            message.error('获取教师列表失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    // 显示弹窗
    const showModal = (record = null) => {
        setEditingRecord(record);
        form.setFieldsValue({
            teacherName: record?.teacherName || '',
            age: record?.age || '',
            gender: record?.gender || 1,
            phoneNumber: record?.phoneNumber || '',
            degree: record?.degree || '',
            academyName: record?.academyName || ''
        });
        setIsModalVisible(true);
    };
    const showEditModal = (record) => {
        setEditingRecord(record);
        form.setFieldsValue({
            teacherName: record.teacherName,
            age: record.age,
            gender: record.gender,
            phoneNumber: record.phoneNumber,
            degree: record.degree ,
            academyId: record.academyId
        });
        setIsModalVisible(true);
    };

    // 提交表单
    const handleOk = (values) => {
        if (editingRecord) {
            updateTeacher({
                id: editingRecord.teacherId,
                academyId: values.academyId,
                teacherName: values.teacherName,
                age: parseInt(values.age),
                gender: parseInt(values.gender),
                phoneNumber: values.phoneNumber,
                degree: values.degree
            })
        } else {
            addTeacher({
                academyId: values.academyId,
                teacherName: values.teacherName,
                age: parseInt(values.age),
                gender: parseInt(values.gender),
                phoneNumber: values.phoneNumber,
                degree: values.degree
            });
        }
        setIsModalVisible(false);
        form.resetFields();
    };

    const addTeacher = async (data) => {
        try {
            const res = await addTeacherInfo(data);
            if (res.code === 200) {
                message.success("新增成功")
                fetchTeacherInfo();
            }
        } catch (error) {
            message.error('新增失败');
            console.error(error);
        }
    }
    const updateTeacher = async (data) => {
        try {
            const res = await updateTeacherInfo(data);
            if (res.code === 200) {
                message.success("修改成功")
                fetchTeacherInfo();
            }
        } catch (error) {
            message.error('修改失败');
            console.error(error);
        }
    }
    const deleteTeacher = async (data) => {
        try {
            const res = await deleteTeacherInfo(data);
            if (res.code === 200) {
                message.success("删除成功")
                fetchTeacherInfo();
            }
        } catch (error) {
            message.error('删除失败');
            console.error(error);
        }
    }
    const batchDeleteTeacher = async (data) => {
        try {
            const res = await batchDeleteTeacherInfo(data);
            if (res.code === 200) {
                message.success("批量删除成功")
                fetchTeacherInfo();
                setSelectedRowKeys([]);
            }
        } catch (error) {
            message.error('批量删除失败');
            console.error(error);
        }
    }

    // 删除单个或批量
    const handleDelete = (id) => {
        Modal.confirm({
            title: '确认删除该教师信息？',
            onOk: () => {
                deleteTeacher({
                    teacherId: id
                })
            }
        });
    };

    // 表格复选配置
    const rowSelection = {
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys) => {
            setSelectedRowKeys(selectedRowKeys);
        },
    };

    const handleCancel = () => {
        setIsModalVisible(false);
        form.resetFields();
    };


    const handleBatchDelete = () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请至少选择一条记录');
            return;
        }

        Modal.confirm({
            title: '确认删除选中的教师信息？',
            onOk: () => {
                batchDeleteTeacher({
                    ids: selectedRowKeys
                });
            }
        });
    };

    // 自定义列渲染序号
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            render: (_, __, index) => index + 1,
        },
        {
            title: '教师姓名',
            dataIndex: 'teacherName',
            align: 'center',
            key: 'teacherName',
        },
        {
            title: '年龄',
            dataIndex: 'age',
            align: 'center',
            key: 'age',
        },
        {
            title: '性别',
            dataIndex: 'gender',
            align: 'center',
            key: 'gender',
            render: gender => (gender === 1 ? '男' : '女'),
        },
        {
            title: '手机号',
            dataIndex: 'phoneNumber',
            align: 'center',
            key: 'phoneNumber',
        },
        {
            title: '学历',
            dataIndex: 'degree',
            align: 'center',
            key: 'degree',
        },
        {
            title: '所属学院',
            dataIndex: 'academyName',
            align: 'center',
            key: 'academyMame'
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            render: (_, record) => (
                <Space>
                    <Button type="link" onClick={() => showEditModal(record)}>编辑</Button>
                    <Button type="link" danger onClick={() => handleDelete(record.id)}>删除</Button>
                </Space>
            ),
        },
    ];

    const handleInputChange = (e) => {
        if (e.target.value === '') {
            fetchTeacherInfo();
        }
        setSearchKeyword(e.target.value);
    };

    const handleSearch = async () => {
        if (!searchKeyword.trim()) {
            message.warning('请输入搜索内容');
            return;
        }

        setLoading(true);
        try {
            const res = await getTeacherInfo(searchKeyword);
            setData(res.data);
        } catch (error) {
            message.error('获取失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div style={{padding: 14}}>
            <div style={{
                marginBottom: 16,
                display: 'flex',
                justifyContent: 'space-between',
                flexWrap: 'wrap',
                gap: 8
            }}>
                <Space>
                    <Button type="primary" onClick={() => showModal()}>新增教师</Button>
                    <Button danger disabled={selectedRowKeys.length === 0} onClick={handleBatchDelete}>
                        批量删除
                    </Button>
                </Space>
                <Space>
                    <AntInput.Search
                        placeholder="请输入教师姓名"
                        value={searchKeyword}
                        onChange={handleInputChange}
                        onSearch={handleSearch}
                        style={{width: 250}}
                        allowClear
                    />
                </Space>
            </div>

            <Table
                rowKey="id"
                dataSource={data}
                columns={columns}
                rowSelection={rowSelection}
                loading={loading}
            />

            <TeacherModal
                visible={isModalVisible}
                onOk={handleOk}
                onCancel={handleCancel}
                editingRecord={editingRecord}
            />
        </div>
    );
};

export default TeacherPage;